import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gt_flutter_admin/app/routes.dart';
import 'package:gt_flutter_admin/models/index.dart';

import 'dept_controller.dart';

class DeptView extends GetView<DeptController> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.only(top: 10, left: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              BrnSmallMainButton(
                title: '新增',
                onTap: () => Get.rootDelegate.toNamed(Routes.DEPT_UPDATE),
              ),
            ],
          ),
        ),
        Obx(
          () => Expanded(
            child: ListView(
              padding: EdgeInsets.all(15),
              children: _buildMenuListTile(controller.deptPage.value.rows),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建菜单项
  List<Widget> _buildMenuListTile(List<dynamic>? list) {
    if (list?.isNotEmpty ?? false) {
      return list!.map<Widget>((element) {
        Dept dept = Dept.fromJson(element);

        if (dept.children?.isNotEmpty ?? false) {
          return ExpansionTile(
            key: Key('${dept.id}'),
            children: _buildMenuListTile(dept.children),
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(dept.deptName),
                Row(
                  children: [
                    IconButton(
                      onPressed: () => Get.rootDelegate.toNamed(
                        Routes.DEPT_UPDATE,
                        arguments: dept,
                      ),
                      icon: Icon(Icons.edit),
                    ),
                    IconButton(
                      onPressed: () => controller.onDeleteDept(dept.id),
                      icon: Icon(Icons.delete),
                    ),
                  ],
                ),
              ],
            ),
          );
        } else {
          return ListTile(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(dept.deptName),
                Row(
                  children: [
                    IconButton(
                      onPressed: () => Get.rootDelegate.toNamed(
                        Routes.DEPT_UPDATE,
                        arguments: dept,
                      ),
                      icon: Icon(Icons.edit),
                    ),
                    IconButton(
                      onPressed: () => controller.onDeleteDept(dept.id),
                      icon: Icon(Icons.delete),
                    ),
                  ],
                ),
              ],
            ),
          );
        }
      }).toList();
    } else {
      return [];
    }
  }
}
